package com.xingkeduo.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WechatFilter implements HandlerInterceptor {

    public final static ThreadLocal<Long> operateIdThreadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        String method = request.getMethod();

        log.info("===============================");
        log.info("url 开始验证:{}", requestURI);
        if (StringUtils.isNotBlank(queryString)) {
            log.info("queryString:{}", queryString);
        }

/*

        try {
            Map<String, String> map = new HashMap<>();
            Enumeration headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String key = (String) headerNames.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
            log.info("header map {}", JSON.toJSONString(map));
        } catch (Exception e) {
            log.error("header map 出错:{}", e);
        }
*/


        try {
            String operator = request.getHeader("operator");
            log.info("操作人:{}", operator);
            operateIdThreadLocal.set(Long.parseLong(operator));
        } catch (NumberFormatException e) {
            operateIdThreadLocal.set(0L);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        operateIdThreadLocal.remove();
    }

}
